package com.phpxiu.app.view.custom;

import android.annotation.TargetApi;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.phpxiu.app.api.listener.WindowLayoutListener;
import com.phpxiu.app.kkylive.R;

import java.lang.ref.WeakReference;

/**
 * Created by WuJinZhou on 2016/5/24.
 */
public class WindowLayout extends RelativeLayout {
    private TopMsgView mTopMsgView;//顶部消息视图
    private boolean isTopMsgViewFront=false;//顶部消息视图是否为最顶层视图
    private WeakReference<WindowLayoutListener>weakRefListener;

    public WindowLayout(Context context) {
        super(context);
        init(context);
    }

    public WindowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public WindowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @TargetApi(21)
    public WindowLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    /**
     * 初始化
     */
    private void init(Context context){
        mTopMsgView=(TopMsgView)LayoutInflater.from(context).inflate(R.layout.top_msg_text_view,null);
        addView(mTopMsgView,new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if(weakRefListener!=null&&weakRefListener.get()!=null){
            weakRefListener.get().onInterceptTouch(ev);
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    /**
     * 添加监听
     */
    public void addWindowLayoutListener(WindowLayoutListener listener){
        if(listener==null){
            if(weakRefListener!=null) {
                weakRefListener.clear();
                weakRefListener = null;
            }
        }else{
            if(weakRefListener!=null) {
                weakRefListener.clear();
            }
            weakRefListener = new WeakReference<WindowLayoutListener>(listener);
        }
    }

    /**
     * 显示顶部提示信息
     */
    public void showTopMsg(String msg){
        if(mTopMsgView!=null){
            if(!isTopMsgViewFront){
                bringChildToFront(mTopMsgView);
                isTopMsgViewFront=true;
            }
            mTopMsgView.show(msg);
        }
    }
}
